const path = require('path');
const express = require('express');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const compression = require('compression');
const cors = require('cors');
const Config = require('config');
const Session = require('./util/session');
const Utility = require('./util/util').Utility;
const HTTPError = require('./util/util').HTTPError;
const userRouter = require('./routes/user');
const friendshipRouter = require('./routes/friendship');
const miscRouter = require('./routes/misc');
const logger = require('flogger').getLogger();

// 导入计划任务模块
require('./util/schedule');

var app = express();

// 路径映射到/WebIM
app.use('/webim', express.static(path.join(__dirname, 'public')));

app.use('/WebIM', function (req, res, next) {
  let reg = /^\/WebIM/;
  if (reg.test(req.originalUrl)) {
    let realUrl = req.originalUrl.replace(reg, '/webim')  // WebIM 重定向到 /webim
      .replace(/^\/webim\/chat/, '/webim/pages/chat')   // /WebIM/chat 重定向到 /webim/pages/chat
      .replace(/^\/webim\/msgcenter/, '/msg/pages/message-center'); // 消息中心重定向
    return res.redirect(realUrl);
  }
  next();
});


app.use(compression());
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors({
  origin: Config.CORS_HOSTS,
  credentials: true
}));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

var authentication = function (req, res, next) {

  // 打印请求日志,包括参数
  logger.info('Request: %s %s %s', (req.method + ' ').substr(0, 4),
    req.originalUrl, JSON.stringify(req.body).replace(/"password":".*?"/, '"password":"**********"'));

  // 不需要权限校验的接口
  let ref = ['/webim/user/login',
    '/webim/user/findOrRegister',
    '/webim/user/reset_password',
    '/webim/user/send_code',
    '/webim/user/verify_code',
    '/webim/user/get_sms_img_code',
    '/webim/user/check_username_available',
    '/webim/user/check_phone_available',
    '/webim/misc/latest_update',
    '/webim/misc/client_version',
    '/webim/message/receive',   // deprecated
    '/webim/misc/message_receive',
    '/webim/misc/online_status_changed',
    '/webim/misc/demo_square'];

  for (let i = 0, len = ref.length; i < len; i++) {
    let reqPath = ref[i];
    if ((typeof reqPath === 'string' && req.path === reqPath)
      || (typeof reqPath === 'object' && reqPath.test(req.path))) {
      return next();
    }
  }

  let currentUserId = Session.getCurrentUserId(req);
  if (!currentUserId) {
    return res.status(403).send('Not loged in.');
  }
  return next();
};

var parameterPreprocessor = function (req, res, next) {
  var prop;
  for (prop in req.body) {
    if (prop.endsWith('Id') || prop.endsWith('Ids')) {
      req.body['encoded' + prop[0].toUpperCase() + prop.substr(1)] = req.body[prop];
      req.body[prop] = Utility.decodeIds(req.body[prop]);
    }
    if (Utility.isEmpty(req.body[prop]) && prop !== 'displayName') {
      return res.status(400).send("Empty " + prop + ".");
    }
  }
  return next();
};

var errorHandler = function (err, req, res, next) {
  if (err instanceof HTTPError) {
    return res.status(err.statusCode).send(err.message);
  }
  Utility.logError(err);
  return res.status(500).send(err.message || 'Unknown error.');
};

app.options('*', cors());
app.use('/webim/pages', require('./midleware/cas'), require('./routes/pages'));
app.all('*', authentication);
app.use(parameterPreprocessor);
app.use('/webim/user', userRouter);
app.use('/webim/friendship', friendshipRouter);
app.use('/webim/misc', miscRouter);
app.use('/webim/message', require('./routes/message'));
app.use('/webim/team', require('./routes/team'));
app.use(errorHandler);


module.exports = app;
